package Thread;

import java.util.concurrent.Semaphore;

public class Demo43 {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("申请资源");
                    semaphore.acquire();
                    System.out.println("获取资源");
                    Thread.sleep(1000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        for (int i = 0; i < 20; i++) {
            new Thread(runnable).start();
        }
    }


    public static void main1(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(4);
        semaphore.acquire();
        System.out.println("1");
        semaphore.acquire();
        System.out.println("2");
        semaphore.acquire();
        System.out.println("3");
        semaphore.acquire();
        System.out.println("4");//不释放信号量被获取完之后再次尝试获取会阻塞
        semaphore.acquire();
    }
}

